<?php

class UserService extends AbstractService
{

    protected function _init()
    {
	$this->setMapper(new UserMapper());
    }

    public function onAfterSave(AbstractModel $model = null)
    {
	if ($model->getId()) {
	    $cacheSlot = new CacheSlotsPk($this->getMapper()->getTableName(), $model->getId());
	    $cacheSlot->delete();	    
	}
	CacheManager::getCache('memcache')->clear('users');
	return true;
    }

    public function generateRecoverCode($user)
    {
	if (!$user->getId()) {
	    return false;
	}
	$code = $this->getMapper()->getRecoveryCodeByUserId($user->getId());
	if ($code) {
	    return $code;
	}
	$code = md5($user->getId() . time());
	if ($this->getMapper()->addRecoveryCode($code, $user->getId())) {
	    return $code;
	}
	return false;
    }

    public function getUserByRecoveryCode($code)
    {
	if (!$code) {
	    return false;
	}
	$userId = $this->getMapper()->getUserByRecoveryCode($code);
	return $this->get($userId);
    }

}